package cn.wildfire.chat.kit.utils;

import androidx.annotation.NonNull;

import com.sourcemuch.im.caiba.CaiBaChatApp;

import java.io.File;
import java.io.IOException;

import cn.wildfire.chat.app.extendsion.utils.SingleThreadDownader;
import okhttp3.OkHttpClient;

/**
 * Created by heavyrainlee on 20/02/2018.
 */

public class DownloadManager {

    private static DownloadManager downloadManager;
    private final OkHttpClient okHttpClient;

    public static DownloadManager get() {
        if (downloadManager == null) {
            downloadManager = new DownloadManager();
        }
        return downloadManager;
    }

    private DownloadManager() {
        okHttpClient = new OkHttpClient();
    }

    public void download(final String url, final String saveDir, final OnDownloadListener listener) {
        download(url, saveDir, listener);
    }

    public void download(final String url, final String saveDir, String name, final OnDownloadListener listener) {
        final String toLocalFilepath = saveDir + "/" + name;
        new SingleThreadDownader(CaiBaChatApp.getContext(), url, toLocalFilepath, new SingleThreadDownader.DownloadReceiverInterface() {
            @Override
            public void downloadFinish() {
                listener.onSuccess(new File(toLocalFilepath));
            }

            @Override
            public void onProgress(long total, long progress, float ratio) {
                listener.onProgress((int) (ratio * 100));
            }

            @Override
            public void downloadFailed() {
                listener.onFail();
            }
        }).work();
    }

    /**
     * @param saveDir
     * @return
     * @throws IOException 判断下载目录是否存在
     */
    private String isExistDir(String saveDir) throws IOException {
        // 下载位置
        File downloadFile = new File(saveDir);
        if (!downloadFile.mkdirs()) {
            downloadFile.createNewFile();
        }
        return downloadFile.getAbsolutePath();
    }

    /**
     * @param url
     * @return 从下载连接中解析出文件名
     */
    @NonNull
    private String getNameFromUrl(String url) {
        return url.substring(url.lastIndexOf("/") + 1);
    }

    public interface OnDownloadListener {
        /**
         * 下载成功
         */
        void onSuccess(File file);

        /**
         * @param progress 下载进度
         */
        void onProgress(int progress);

        /**
         * 下载失败
         */
        void onFail();
    }
}